package handler

import (
	"ideatools/application/constant"
	"ideatools/application/constant/enums"
	"ideatools/application/core/mycache"
	"ideatools/application/db/dbservice"
	"ideatools/application/pkgs/mylog"
	"ideatools/application/service"
	"ideatools/pkg/chat"
)

var GptService chat.IGpt //用户工具

func InitGpt() {
	GptService = &chat.GptLocal{}             // 创建一个本地 GPT 服务对象
	err := GptService.InitGpt(GetGptConfig()) // 初始化 GPT 服务对象，使用预先配置的 GPT 配置
	if err != nil {
		mylog.Error("InitGpt error:" + err.Error())
	}

}

func GetGptConfig() *chat.GptConfig {
	conf := dbservice.Conf()
	gptConfig := &chat.GptConfig{
		OpenAiKey:         conf.Get(constant.ConfigKeySysOpenAiKey),
		IdeaToolKey:       conf.Get(constant.ConfigKeySysIdeaToolsKey),
		ProxyType:         conf.Get(constant.ConfigKeyProxyType),
		ProxyLocalUrl:     conf.Get(constant.ConfigKeyProxyUrlLocal),
		ProxyServerUrl:    conf.Get(constant.ConfigKeyProxyServeApi),
		GptModel:          conf.Get(constant.ConfigKeyGptModel),
		BackAuthorization: conf.Get(constant.ConfigKeyBackAuthorization),
		IsStream:          true,
	}

	if gptConfig.ProxyType == enums.ProxyTypeZhiJianServe {
		gptConfig.ProxyServerUrl = GetZhiJianProxyUrl()
	}

	return gptConfig
}

func GetZhiJianProxyUrl() string {
	//如果缓存有数据 直接从缓存拿
	if mycache.GetZhiJianChatProxyUrl() != "" {
		return mycache.GetZhiJianChatProxyUrl()
	}

	proxyInfo := service.NewBackService().GetZhijianProxyInfo()
	if proxyInfo == nil || proxyInfo.Code != enums.RespCodeOk {
		mylog.Error("GetZhiJianProxyUrl() proxyInfo == nil ||  proxyInfo.Code != enums.RespCodeOk")
		return ""
	}
	url := proxyInfo.Data.(string)
	mylog.Debug("GetZhiJianProxyUrl() value:" + url)

	//复制给缓存
	mycache.SetZhiJianChatProxyUrl(url)

	return url
}

func SetGptConfig(handlerStream chat.StreamHandler) *chat.GptConfig {
	gptConfig := GetGptConfig()

	gptConfig.StreamHandle = handlerStream
	if handlerStream == nil {
		gptConfig.IsStream = false
	}
	if GptService != nil {
		err := GptService.UpdateConfig(gptConfig)
		if err != nil {
			mylog.Error(err.Error())
		}
	}
	return gptConfig
}
